#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# @Time    : 2021/8/6 上午9:59
# @Author  : Samge
import json
from concurrent import futures
import grpc
import logging
import time

from rpc_package.helloWord_pb2 import HelloReply
from rpc_package.helloWord_pb2_grpc import HelloWorldServiceServicer, add_HelloWorldServiceServicer_to_server


class Hello(HelloWorldServiceServicer):

    def test(self, request, context):
        print(f"rpc服务，test 接受到参数：{request.name}")
        return HelloReply(code=200, message='test succeed!', data=None)

    # 这里实现我们定义的接口
    def SayHello(self, request, context):
        print(f"rpc服务，SayHello 接受到参数：{request.name}")
        return HelloReply(code=200, message=f'Hello, {request.name}!', data=json.dumps({'info': 'data info here'}))


def serve():
    # 这里通过thread pool来并发处理server的任务
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))

    # 将对应的任务处理函数添加到rpc server中
    add_HelloWorldServiceServicer_to_server(Hello(), server)

    # 这里使用的非安全接口，世界gRPC支持TLS/SSL安全连接，以及各种鉴权机制
    server.add_insecure_port('[::]:50000')
    server.start()

    print("rpc服务已启动")

    try:
        while True:
            time.sleep(60 * 60 * 24)
    except KeyboardInterrupt:
        server.stop(0)


if __name__ == "__main__":
    logging.basicConfig()
    serve()
